package com.fancy.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.fancy.service.IUpdateUserVipStateService;
import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Created by 54110 on 2020/8/19.
 */
@RestController
public class AlipayController {

    @Autowired
    private IUpdateUserVipStateService updateUserVipStateService;

     String userid;

    @RequestMapping("/pay")
    //@ResponseBody
    public String pay(HttpServletRequest httpRequest,
                      HttpServletResponse httpResponse, @RequestParam("userId") String userId) throws ServletException, IOException {

        userid = userId;

        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do",
                "2021000116692599",
                "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCh02yXLXV9lIDXUCFbEtY+hPzymULyYkljIfBfOTg6gXMZWtH8KSIwWP3UYm+ejfCakeKPHCALjQU/f8e9mymwNjg/D3ht+M9b5U90B00TBiM6EZnoPg+cmC8SmDQ8W/3re5KTfQu4QUvgJXXsVbim99wxL4bYtaOHEEGvHON+BYwmeACxWvWKWfsDexy6S59FUGKuWfkjh41kNaDt1DIKSOaA2De3l+mYAn7DwMHui9BbqYo1VLhyf30NKkH75UJJHs5q6WDvvzo6p3aRLBQcEf59cVwdWEYQLs7hEsI0CP2QjKJzwlmicQAfJJuEYFg3jS61It5iczQdA+ACJ9GrAgMBAAECggEALxLJa9CVdMpWEEwG5+8600TsL8XVa5ybrHKa8Zg7ewlc6es5Whi9EUNR0w4vWfgAHXaCaQ7NY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UqMAoVjQ0VEkD+3YA2WeXiiaVMM7BCE3fOT74CR8TO4RYKlN/OgQ==",
                "json",
                "UTF-8",
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAslW1XuWv3ZAyrt9UKraQPqg0bqcoFA3+ebOGMKfKKbbwBl3tiLu3vgCS33RFo2tjixRxG3K6zVCf+WTzZRG9LU2E21UnBxPGI+cNkksLud8Ydzkyyd/jfMO5W6V+lxCkfIlCK/WAtKLOFfWMOqWMC+RYQN/OI0FeHvCUNtkgvGJilRSKC0uAZl3rxyR+/ELPdaVb+M6Vdlc4H7+I7cAORWPQIsH5IS36zyejvJydVZxk2YlilHCSPdugcZKX9McH5gOQXe0X9Y+dcNCdQUGkZWd6eorOFiwBzlMzEnwzXQZXW85T4TATOl6zBmXNO9eMjxI1pg8sFxkwKliysl5JFQIDAQAB",
                "RSA2");
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); //创建API对应的request

        //alipayRequest.setReturnUrl( "http://331t2j2729.zicp.vip/returlCallBack" );
        //支付宝的回调地址,支付结果异步通知

        alipayRequest.setNotifyUrl("http://34c241e630.goho.co/returnCallBack"); //在公共参数中设置回跳和通知地址

        //alipayRequest.putOtherTextParam("app_auth_token", "201611BB8xxxxxxxxxxxxxxxxxxxedcecde6");//如果 ISV 代商家接入电脑网站支付能力，则需要传入 app_auth_token，使用第三方应用授权；自研开发模式请忽略

//        String orderNum = UUID.randomUUID().toString();

        Long orderNum = new Date().getTime();

//        System.out.println(orderNum);

        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":" + orderNum + "," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":38.8," +
                "    \"subject\":\"会员\"," +
                "    \"body\":\"一个月的黑胶会员\"," +
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                "    \"extend_params\":{" +
                "    \"sys_service_provider_id\":\"2088511833207846\"" +
                "    }" +
                "  }"); //填充业务参数
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        /*httpResponse.setContentType("text/html;charset=" + "utf-8");
        httpResponse.getWriter().write(form); //直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();*/

        return form;
    }

    @RequestMapping("/returnCallBack")
    public String returnCallBack(HttpServletRequest request) throws AlipayApiException {

        Integer id = Integer.parseInt(userid);

        // public String returlCallBack(Map<String, String> paramsMap) throws AlipayApiException {
        Map<String, String> paramsMap = convertRequestParamsToMap(request);
        boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap,
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAslW1XuWv3ZAyrt9UKraQPqg0bqcoFA3+ebOGMKfKKbbwBl3tiLu3vgCS33RFo2tjixRxG3K6zVCf+WTzZRG9LU2E21UnBxPGI+cNkksLud8Ydzkyyd/jfMO5W6V+lxCkfIlCK/WAtKLOFfWMOqWMC+RYQN/OI0FeHvCUNtkgvGJilRSKC0uAZl3rxyR+/ELPdaVb+M6Vdlc4H7+I7cAORWPQIsH5IS36zyejvJydVZxk2YlilHCSPdugcZKX9McH5gOQXe0X9Y+dcNCdQUGkZWd6eorOFiwBzlMzEnwzXQZXW85T4TATOl6zBmXNO9eMjxI1pg8sFxkwKliysl5JFQIDAQAB",
                "utf-8",
                "RSA2"); //调用SDK验证签名

        if (signVerified) {
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure

            //System.out.println(id);
            updateUserVipStateService.updateUserVipState(id);
            return "success";
        } else {
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            return "fail";
        }
    }

    // 将request中的参数转换成Map
    private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<>();

        //System.out.println(request);

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }
}
